<template>
	<d2-container>
		<template>
			<div class="form-area">
				<el-form ref="addForm" :model="formData" :rules="rules" label-width="110px" style="height:auto">
					<div class="form-title"><h3>基本信息</h3></div>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="入库单编号" prop="stockInOrder.stockInOrderNo">
								<el-input type="text" v-model="formData.stockInOrder.stockInOrderNo" placeholder="系统自动生成" readonly></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="采购单编号" prop="stockInOrder.relatedOrderNo">
								<el-input type="text" v-model="formData.stockInOrder.relatedOrderNo" placeholder="请选择采购单" readonly>
									<template slot="append">
										<el-button size="small" @click="showPurchaseOrderPage">选择</el-button>
									</template>
								</el-input>
							</el-form-item>
						</el-col>
					</el-row>
          <el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="供应商名称" prop="stockInOrder.supplierName">
								<el-input type="text" v-model="formData.stockInOrder.supplierName" readonly></el-input>
							</el-form-item>
						</el-col>
            <el-col :span="12">
							<el-form-item label="供应商编码" prop="stockInOrder.supplierCode">
								<el-input type="text" v-model="formData.stockInOrder.supplierCode" readonly></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
            <el-col :span="12">
							<el-form-item label="入库状态" prop="stockInOrder.stockInStatus">
								<el-input :value="formData.stockInOrder.stockInStatus == 1 ? '未入库' : formData.stockInOrder.stockStatus == 2 ? '部分入库' : '全部入库'" readonly></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="入库门店" prop="stockInOrder.shopId">
								<el-select v-model="formData.stockInOrder.shopId" placeholder="请选择入库门店" style="width: 100%;" @change="selectShop()">
									<el-option v-for="(item, key) of shopList" :key="key" :value="item.id" :label="item.shopName"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="库存类型" prop="stockInOrder.stockType">
                <el-select v-model="formData.stockInOrder.stockType" placeholder="请选择库存类型" style="width: 100%;" @change="selectStockType()">
									<el-option value="1" label="线下库存"></el-option>
									<el-option value="2" label="线上库存"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="入库仓库" prop="stockInOrder.repositoryId">
								<el-select v-model="formData.stockInOrder.repositoryId" placeholder="请选择入库仓库" style="width: 100%;" @change="selectRepository()">
									<el-option v-for="(item, key) of repositoryList" :key="key" :value="item.id" :label="item.repositoryName"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="备注" prop="stockInOrder.remark">
								<el-input type="textarea" :rows="4" v-model="formData.stockInOrder.remark" placeholder="请输入备注"></el-input>
							</el-form-item>
						</el-col>
					</el-row>

					<div class="form-title"><h3>审核信息</h3></div>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="提交人" prop="submitor">
								<el-input type="text" v-model="formData.stockInOrder.submitor" placeholder="提交人" readonly></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="提交时间" prop="submitTime">
								<el-date-picker v-model="formData.stockInOrder.submitTime" type="datetime" placeholder="提交时间" readonly style="width: 100%;"></el-date-picker>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="审核人" prop="auditor">
								<el-input type="text" v-model="formData.stockInOrder.auditor" placeholder="审核人" readonly></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="审核时间" prop="authTime">
								<el-date-picker v-model="formData.stockInOrder.authTime" type="datetime" placeholder="审核时间" readonly style="width: 100%;"></el-date-picker>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="审核状态" prop="status">
								<el-input :value="formData.stockInOrder.status == 1 ? '审核中' : formData.stockInOrder.status == 2 ? '审核通过' : formData.stockInOrder.status == 3 ? '审核不通过' : '未提交'" readonly></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="审核说明" prop="authDesc">
								<el-input type="textarea" :rows="4" v-model="formData.stockInOrder.authDesc" placeholder="审核说明" readonly></el-input>
							</el-form-item>
						</el-col>
					</el-row>

					<div class="form-title">
						<h3>明细信息</h3>
					</div>

					<el-row :gutter="20">
						<el-col :span="24">
							<!-- 入库单明细-关联采购单 -->
							<template>
								<div class="form-table">
									<el-table :data="formData.stockInOrder.detailList" stripe border style="width: 100%">
										<el-table-column prop="index" label="序号" width="50" type="index"></el-table-column>
										<el-table-column prop="productName" label="商品名称"></el-table-column>
                    <el-table-column prop="productCode" label="商品编码"></el-table-column>
										<el-table-column prop="productSkuName" label="SKU名称"></el-table-column>
										<el-table-column prop="productSkuCode" label="SKU编码"></el-table-column>
                    <el-table-column prop="unitQuantity" label="采购数量"></el-table-column>
										<el-table-column prop="unitName" label="采购单位"></el-table-column>
										<el-table-column prop="stockInedQuantity" label="已入库数量"></el-table-column>
										<el-table-column prop="tobeStockInQuantity" label="待入库数量"></el-table-column>
                    <el-table-column prop="stockIningQuantity" label="入库中数量"></el-table-column>
									  <el-table-column prop="stockInableQuantity" label="可入库数量"></el-table-column>
                    <el-table-column prop="stockInQuantity" label="本次入库数量">
											<template slot-scope="scope">
												<el-input v-model="scope.row.stockInQuantity" clearable placeholder="请设置数量" @blur="setQuantity(scope.$index, scope.row)"></el-input>
											</template>
										</el-table-column>
                    <el-table-column prop="stockInUnit" label="入库单位"></el-table-column>
										<el-table-column label="操作" width="80">
											<template slot-scope="scope">
												<el-button plain type="primary" size="small" @click.native.prevent="deleteRow(scope.$index, scope.row)">移除</el-button>
											</template>
										</el-table-column>
									</el-table>
								</div>
							</template>
						</el-col>
					</el-row>

					<!-- 按钮 -->
					<el-row :gutter="20">
						<el-col :span="24">
							<el-form-item>
              <div class="form-submit">
								<el-button class="form-submit-btn" type="primary" @click="save('addForm')">保存</el-button>
								<el-button class="form-submit-btn" type="primary" @click="saveAndSubmit('addForm')">保存并提交</el-button>
								<el-button class="form-cancle-btn" @click="cancel()">取消</el-button>
							</div>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</div>
		</template>

		<!-- 弹框-选择采购单 -->
		<template>
			<el-dialog title="选择采购单" width="70%" :visible.sync="showPurchaseOrderList" :before-close="handleClose">
				<div class="dialog-search">
					<el-form class="inline-form" :inline="true" :model="searchPurchaseOrderForm">
						<el-form-item label="采购单编号" prop="purchaseOrderNo">
							<el-input v-model="searchPurchaseOrderForm.purchaseOrderNo" placeholder="请输入采购单编号" style="width: 120%"></el-input>
						</el-form-item>
						<el-button type="primary" size="medium" @click="fetchDataPurchaseOrder" style="margin-left: 5%">搜索</el-button>
					</el-form>
				</div>
				<div class="form-table">
					<el-table :data="tableDataPurchaseOrder" stripe border style="width: 100%">
						<el-table-column prop="index" label="序号" width="50" type="index"></el-table-column>
						<el-table-column prop="orderNo" label="采购单编号"></el-table-column>
						<el-table-column prop="supplierName" label="供应商名称"></el-table-column>
						<el-table-column prop="amountTotal" label="总金额(元)"></el-table-column>
						<el-table-column prop="paidAmount" label="已付金额(元)" width="110"></el-table-column>
						<el-table-column prop="toPayAmount" label="待付金额(元)" width="110"></el-table-column>
						<el-table-column prop="stockStatus" label="入库状态" width="80">
							<template slot-scope="scope">
								<span v-if="scope.row.stockStatus == 1">未入库</span>
								<span v-if="scope.row.stockStatus == 2">部分入库</span>
								<span v-if="scope.row.stockStatus == 3">全部入库</span>
							</template>
						</el-table-column>
						<el-table-column label="操作" width="80">
							<template slot-scope="scope">
								<el-button v-if="scope.row.id != purchaseOrderId" type="primary" plain size="small" @click="purchaseOrderId = scope.row.id">选择</el-button>
								<el-button v-if="scope.row.id == purchaseOrderId" type="primary" size="small" @click="purchaseOrderId = ''">已选</el-button>
							</template>
						</el-table-column>
					</el-table>
				</div>

				<div class="page dialog-page">
					<el-pagination
						background
						@current-change="handleCurrentChangePurchaseOrder"
						:current-page="currentPagePurchaseOrder"
						:page-sizes="[10, 20, 50, 100]"
						:page-size="pageSizePurchaseOrder"
						layout="total, prev, pager, next"
						:total="totalPurchaseOrder"
					></el-pagination>
				</div>

				<div class="dialog-footer" slot="footer">
					<el-button type="primary" @click="confirmPurchaseOrder()">确定</el-button>
					<el-button @click="closeShowPurchaseOrderList()">取消</el-button>
				</div>
			</el-dialog>
		</template>
	</d2-container>
</template>
<script>
import { mapActions, mapState } from 'vuex'
import { getStockIningQuantity, savePurchaseStockInOrder, saveAndSubmitPurchaseStockInOrder } from '@api/stockIn/stockInOrder'
import { getShops } from '@api/shop/shop'
import { findAllListEnable } from '@api/repository/repositoryInfo'
import { pageToStockInOrder, listToStockInOrderDetail } from '@api/purchase/purchase'
export default {
  name: 'stockIn-purchaseStockInAdd',
  data () {
    return {
      formData: {
        stockInOrder: {
          stockInOrderNo: '',
          shopId: '',
          supplierId: '',
          supplierCode: '',
          supplierName: '',
          repositoryId: '',
          repositoryName: '',
          stockInQuantity: 0,
          relatedOrderId: '',
          relatedOrderNo: '',
          stockInType: '1',
          stockType: '',
          status: '0',
          stockInStatus: '1',
          remark: '',
          detailList: []
        }
      },

      shopList: [],
      repositoryList: [],

      showPurchaseOrderList: false,
      searchPurchaseOrderForm: {
        purchaseOrderNo: ''
      },
      tableDataPurchaseOrder: [],
      currentPagePurchaseOrder: 1,
      pageSizePurchaseOrder: 10,
      totalPurchaseOrder: 0,
      purchaseOrderId: '',
      purchaseDetailSelectId: '',

      rules: {
        'stockInOrder.relatedOrderNo': [{ required: true, message: '请选择采购单', trigger: 'blur' }],
        'stockInOrder.shopId': [{ required: true, message: '请选择门店', trigger: 'blur' }],
        'stockInOrder.repositoryId': [{ required: true, message: '请选择仓库', trigger: 'blur' }],
        'stockInOrder.stockType': [{ required: true, message: '请选择库存类型', trigger: 'blur' }],
        'stockInOrder.remark': [{ required: true, message: '请输入备注', trigger: 'blur' }, { min: 1, max: 256, message: '长度在 1 到 256 个字符', trigger: 'blur' }]
      },

	  isReturnList: false // 关闭页面是否返回列表
    }
  },
  created () {},
  mounted () {
    var toStockInOrderAddFlag = sessionStorage.getItem('toStockInOrderAddFlag')
    if (toStockInOrderAddFlag == undefined || toStockInOrderAddFlag == 'fromStockInOrderListPage') {
      // 从入库单列表点“新建采购入库”进入页面
    } else if (toStockInOrderAddFlag == 'fromPurchaseOrder') {
      // 从采购单列表点击“去入库”进入页面
      this.initFromPsPurchaseOrder()
    }
    this.getShopList()
  },
  beforeDestroy () {
	  if (this.isReturnList) {
      this.clearSessionStorage()
      // 跳转到列表页面
      this.$router.push({
		  path: 'stockIn/purchaseStockInList',
		  name: 'stockIn-purchaseStockInList',
		  params: ''
      })
	  }
  },
  watch: {},
  computed: {
    ...mapState('d2admin/page', ['opened', 'current'])
  },
  methods: {
    ...mapActions('d2admin/page', ['close']),
    getShopList () {
      getShops({}).then(res => {
        if (res.code == '000000') {
          this.shopList = res.data
        } else {
          this.$message({ message: '门店加载失败，请重试!', type: 'error' })
        }
      })
        .catch(err => {
          console.log('err', err)
        })
    },
    selectShop () {
      this.formData.stockInOrder.stockType = ''
      this.repositoryList = []
      this.formData.stockInOrder.repositoryId = ''
      this.formData.stockInOrder.repositoryName = ''
    },
    selectStockType () {
      this.repositoryList = []
      this.formData.stockInOrder.repositoryId = ''
      this.formData.stockInOrder.repositoryName = ''
      this.getRepositoryList()
    },
    getRepositoryList () {
      findAllListEnable({ stockType: this.formData.stockInOrder.stockType }).then(res => {
        if (res.code == '000000') {
			  let list = res.data
			  list.forEach(item => {
				  if (item.shopId == this.formData.stockInOrder.shopId) {
					  this.repositoryList.push(item)
				  }
			  })
        } else {
          this.$message({ message: '仓库加载失败，请重试!', type: 'error' })
        }
      })
        .catch(err => {
          console.log('err', err)
        })
    },
    selectRepository () {
      for (let index in this.repositoryList) {
        if (this.repositoryList[index].id == this.formData.stockInOrder.repositoryId) {
          this.formData.stockInOrder.repositoryName = this.repositoryList[index].repositoryName
        }
      }
    },

    showPurchaseOrderPage () {
      this.fetchDataPurchaseOrder()
      this.showPurchaseOrderList = true
    },
    fetchDataPurchaseOrder () {
      this.loading = true
      pageToStockInOrder({
        keyWord: this.searchPurchaseOrderForm.purchaseOrderNo,
        currentPage: this.currentPagePurchaseOrder,
        pageSize: this.pageSizePurchaseOrder
      })
        .then(res => {
          for (let index in res.data.content) {
            res.data.content[index].isSeleted = false
          }
          this.tableDataPurchaseOrder = res.data.content
          this.totalPurchaseOrder = res.data.total
          this.loading = false
        })
        .catch(err => {
          console.log('err', err)
          this.loading = false
        })
    },
    handleSizeChangePurchaseOrder (val) {
      this.pageSizePurchaseOrder = val
      this.fetchDataPurchaseOrder()
    },
    handleCurrentChangePurchaseOrder (val) {
      this.currentPagePurchaseOrder = val
      this.fetchDataPurchaseOrder()
    },
    closeShowPurchaseOrderList () {
      this.searchPurchaseOrderForm = {
        purchaseOrderNo: ''
      }
      this.purchaseOrderId = ''
      this.showPurchaseOrderList = false
    },
    handleClose (done) {
      this.searchPurchaseOrderForm = {
        purchaseOrderNo: ''
      }
      this.purchaseOrderId = ''
      done()
    },
    confirmPurchaseOrder () {
      if (this.purchaseOrderId == undefined || this.purchaseOrderId == '') {
        this.$message.warning('请先选择采购单')
        return false
      }
      for (var i in this.tableDataPurchaseOrder) {
        if (this.tableDataPurchaseOrder[i].id == this.purchaseOrderId) {
          this.formData.stockInOrder.supplierId = this.tableDataPurchaseOrder[i].supplierId
          this.formData.stockInOrder.supplierCode = this.tableDataPurchaseOrder[i].supplierCode
          this.formData.stockInOrder.supplierName = this.tableDataPurchaseOrder[i].supplierName
          this.formData.stockInOrder.relatedOrderId = this.tableDataPurchaseOrder[i].id
          this.formData.stockInOrder.relatedOrderNo = this.tableDataPurchaseOrder[i].orderNo
        }
      }
      // 加载采购单明细列表
      this.loadStockStatusPurchaseOrderDetailList()
      this.closeShowPurchaseOrderList()
    },
    loadStockStatusPurchaseOrderDetailList () {
      listToStockInOrderDetail({
        orderId: this.purchaseOrderId
      }).then(res => {
        if (res.code == '000000') {
          this.formData.stockInOrder.detailList = []
          let list = res.data
          list.forEach(item => {
            let stockIningQuantity = 0
            let stockInableQuantity = 0
            getStockIningQuantity({
              orderId: item.orderId,
              skuId: item.productSkuId
            }).then(res => {
              if (res.code == '000000') {
                stockIningQuantity = res.data
                stockInableQuantity = item.tobeStockInQuantity - stockIningQuantity
              }

              if (this.purchaseDetailSelectId != undefined && this.purchaseDetailSelectId != '') {
                if (this.purchaseDetailSelectId == item.id) {
                  this.formData.stockInOrder.detailList.push({
                    productId: item.productId,
                    productCode: item.productCode,
                    productName: item.productName,
                    productSkuId: item.productSkuId,
                    productSkuCode: item.productSkuCode,
                    productSkuName: item.productSkuName,
                    stockInQuantity: stockInableQuantity,
                    stockInUnit: item.skuUnitName,
                    unitQuantity: item.purchaseQuantity,
                    unitId: item.unitId,
                    unitName: item.unitName,
                    unitRatio: item.unitRatio,
                    relatedOrderId: item.orderId,
                    relatedOrderNo: item.orderNo,
                    relatedOrderDetailId: item.id,
                    relatedOrderDetailNo: item.orderSubNo,
                    stockInedQuantity: item.stockInQuantity,
                    tobeStockInQuantity: item.tobeStockInQuantity,
                    stockIningQuantity: stockIningQuantity,
                    stockInableQuantity: stockInableQuantity
                  })
                }
              } else {
                this.formData.stockInOrder.detailList.push({
                  productId: item.productId,
                  productCode: item.productCode,
                  productName: item.productName,
                  productSkuId: item.productSkuId,
                  productSkuCode: item.productSkuCode,
                  productSkuName: item.productSkuName,
                  stockInQuantity: stockInableQuantity,
                  stockInUnit: item.skuUnitName,
                  unitQuantity: item.purchaseQuantity,
                  unitId: item.unitId,
                  unitName: item.unitName,
                  unitRatio: item.unitRatio,
                  relatedOrderId: item.orderId,
                  relatedOrderNo: item.orderNo,
                  relatedOrderDetailId: item.id,
                  relatedOrderDetailNo: item.orderSubNo,
                  stockInedQuantity: item.stockInQuantity,
                  tobeStockInQuantity: item.tobeStockInQuantity,
                  stockIningQuantity: stockIningQuantity,
                  stockInableQuantity: stockInableQuantity
                })
              }
              // 刷新入库总数量
              this.setTotalQuantity()
            })
          })
        } else {
          this.$message({ message: '采购单明细列表加载失败，请重试!', type: 'error' })
        }
      })
        .catch(err => {
          console.log('err', err)
        })
    },

    // 刷新入库总数量
    setTotalQuantity () {
      let totalQuantity = 0
      for (let i in this.formData.stockInOrder.detailList) {
        let stockInQuantity = this.formData.stockInOrder.detailList[i].stockInQuantity
        if (stockInQuantity == undefined) {
          stockInQuantity = 0
        }
        totalQuantity = Number(totalQuantity) + Number(stockInQuantity)
      }
      this.formData.stockInOrder.stockInQuantity = totalQuantity
    },
    setQuantity (index, row) {
      if (row.stockInQuantity === '') {
        this.$message.warning('数量不能为空')
        return false
      }
      let boolean = new RegExp('^[1-9][0-9]*$').test(row.stockInQuantity)
      if (!boolean) {
        this.$message.warning('数量必须是正整数')
        return false
      }
      if (row.stockInQuantity == 0) {
        this.$message.warning('本次入库数量必须大于0')
        return false
      }
      if (row.stockInQuantity > row.stockInableQuantity) {
        this.$message.warning('本次入库数量必须小于或等于可入库数量')
        return false
      }
      // 刷新入库总数量
      this.setTotalQuantity()
    },
    deleteRow (index, row) {
      this.$confirm('确认移除商品名称为【' + row.productName + '】数据？').then(_ => {
        for (var i = 0; i < this.formData.stockInOrder.detailList.length; i++) {
          if (i == index) {
            this.formData.stockInOrder.detailList.splice(i, 1)
            // 刷新入库总数量
            this.setTotalQuantity()
            break
          }
        }
      })
    },
    cancel () {
      // 关闭当前窗口
      let tagName = this.current
      this.close({ tagName })
    },
    save (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.checkData()) {
            this.loading = true
            savePurchaseStockInOrder(this.formData.stockInOrder)
              .then(res => {
                if (res.code == '000000') {
                  this.$message({ message: res.message, type: 'success' })
                  this.loading = false
				  this.isReturnList = true
                  this.cancel()
                } else {
                  this.$message({ message: res.message, type: 'error' })
                }
              })
              .catch(err => {
                console.log('err', err)
                this.loading = false
              })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    saveAndSubmit (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.checkData()) {
            this.loading = true
            saveAndSubmitPurchaseStockInOrder(this.formData.stockInOrder)
              .then(res => {
                if (res.code == '000000') {
                  this.$message({ message: res.message, type: 'success' })
                  this.loading = false
				  this.isReturnList = true
                  this.cancel()
                } else {
                  this.$message({ message: res.message, type: 'error' })
                }
              })
              .catch(err => {
                console.log('err', err)
                this.loading = false
              })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    checkData () {
      if (this.formData.stockInOrder.detailList.length == 0) {
        this.$message.warning('请选择采购单')
        return false
      }

      let checkQuantity = false
      for (let i in this.formData.stockInOrder.detailList) {
        let row = this.formData.stockInOrder.detailList[i]

        if (row.stockInQuantity === '') {
          checkQuantity = true
          break
        }
        let boolean = new RegExp('^[1-9][0-9]*$').test(row.stockInQuantity)
        if (!boolean) {
          checkQuantity = true
          break
        }
        if (row.stockInQuantity == 0) {
          checkQuantity = true
          break
        }
        if (row.stockInQuantity > row.stockInableQuantity) {
          checkQuantity = true
          break
        }
      }

      if (checkQuantity) {
        this.$message.warning('请检查数量')
        return false
      }

      return true
    },
    initFromPsPurchaseOrder () {
      var purchaseOrderStr = sessionStorage.getItem('stockInOrder_add_purchaseOrder')
      if (purchaseOrderStr != undefined) {
        var purchaseOrder = JSON.parse(purchaseOrderStr)
        this.purchaseOrderId = purchaseOrder.id
        this.purchaseDetailSelectId = purchaseOrder.purchaseOrderDetailId
        this.formData.stockInOrder.supplierId = purchaseOrder.supplierId
        this.formData.stockInOrder.supplierCode = purchaseOrder.supplierCode
        this.formData.stockInOrder.supplierName = purchaseOrder.supplierName
        this.formData.stockInOrder.relatedOrderId = purchaseOrder.id
        this.formData.stockInOrder.relatedOrderNo = purchaseOrder.orderNo
        // 加载采购单明细列表
        this.loadStockStatusPurchaseOrderDetailList()
      }
    },
    clearSessionStorage () {
      sessionStorage.removeItem('toStockInOrderAddFlag')
      sessionStorage.removeItem('stockInOrder_add_purchaseOrder')
    }
  }
}
</script>
